package cn.chenxiejia;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import static cn.chenxiejia.Thread1.condition;
import static cn.chenxiejia.Thread1.lock;

/**
 * @version : V1.0
 * @program: maven
 * @ClassName: Gbf1
 * @Description: ReentrantLock重入锁与condition联用实现await功能
 * @Author: chenxiejia
 * @Date: 2
 * 2022/2/17 8:33
 */
public class Gbf1 {
    public static void main(String[] args) throws InterruptedException {
        var thread1 = new Thread1();
        Thread t1 = new Thread(thread1);
        t1.start();
        //睡眠两秒让condition.await先执行
        TimeUnit.SECONDS.sleep(3);
        //必须与lock一起用
        lock.lock();
        //通知thread1线程可以启动了
        condition.signal();
        lock.unlock();
    }
}

class Thread1 implements Runnable {
    public static ReentrantLock lock = new ReentrantLock();
    public static Condition condition = lock.newCondition();

    @Override
    public void run() {
        System.out.println("thread1开始");
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println("thread1挂起");
            lock.lock();
            condition.await();
            lock.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("thead1启动");
    }
}
